package com.example.videodisplay;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.videodisplay.entity.Account;

import org.litepal.LitePal;

import java.util.List;

/**
 * @author xioatie
 */
public class RegisterActivity extends AppCompatActivity {

    private EditText username;
    private EditText password;
    private EditText password2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }
    private void initView(){
        Button login = findViewById(R.id.reg_btn_login);
        login.setOnClickListener(v -> finish());
        Button sure = findViewById(R.id.reg_btn_sure);
        sure.setOnClickListener(v -> reg());
        username = findViewById(R.id.reg_username);
        password = findViewById(R.id.reg_password);
        password2 = findViewById(R.id.reg_password2);
    }

    private void reg() {
        String user = username.getText().toString().trim();
        String pass = password.getText().toString().trim();
        String pass1 = password2.getText().toString().trim();
        if(user.isEmpty()||pass.isEmpty()||pass1.isEmpty()){
            Toast.makeText(this, "不能为空", Toast.LENGTH_SHORT).show();
        }else if(!pass.equals(pass1)){
            Toast.makeText(this, "密码不一致", Toast.LENGTH_SHORT).show();
        }else{
            List<Account> all = LitePal.findAll(Account.class);
            for (Account account : all){
                if(account.getUserName().equals(user)) {
                    Toast.makeText(this, "用户名重复", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            Account account = new Account(user, pass);
            account.save();
            Toast.makeText(this, "注册成功，返回登陆", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}